import axios from 'axios';
import { message } from 'antd';
import { eventBus, EVENT_TYPES } from './eventBus';

// 创建axios实例
const request = axios.create({
  baseURL: '',
  timeout: 500000,
  headers: {
    //'Content-Type': 'application/x-www-form-urlencoded',
		'Authorization':`Bearer ${localStorage.getItem('token')}`
  },
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 在这里可以添加token等认证信息
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    const { data } = response;
    
    // 如果返回的数据中有code字段，根据code值进行相应处理
    if (data && typeof data === 'object' && 'code' in data) {
      if (data.code === 403) {
        // 未授权，清除本地token，跳转到登录页面
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        localStorage.removeItem('auth');
        // 触发导航事件
        eventBus.emit(EVENT_TYPES.NAVIGATE, '/login');
        return Promise.reject(new Error(data.message || data.msg || '登录已过期，请重新登录'));
      }
      
      if (data.code !== 200 && data.code !== 0) {
        // 请求成功但业务处理失败
        message.error(data.message || data.msg || '操作失败');
        return Promise.reject(new Error(data.message || data.msg || '操作失败'));
      }
    }  
    return data;
  },
  (error) => {
    if (error.response) {
      const { status } = error.response;
      
      if (status === 401 || status === 403) {
        handleUnauthorized()
      } else {
        message.error(error.response?.data?.message || `请求失败(${status})`);
      }
    } else {
      message.error('网络错误，请检查您的网络连接');
    }
    return Promise.reject(error);
  }
);

export const handleUnauthorized = () => {
  // 未授权，清除本地token，跳转到登录页面
  localStorage.removeItem('token');
  localStorage.removeItem('userInfo');
  localStorage.removeItem('auth');
  // 触发导航事件
  eventBus.emit(EVENT_TYPES.NAVIGATE, '/login');
  message.error('登录已过期，请重新登录');
}

// 封装get请求
export const get = async <T>(url: string, params?: any): Promise<T> => {
  return request.get(url, { params });
};

// 封装post请求
export const post = async <T>(url: string, data?: any, headers?: any, signal?: AbortSignal): Promise<T> => {
  return request.post(url, data, { headers, signal });
};

// 封装put请求
export const put = async <T>(url: string, data?: any): Promise<T> => {
  return request.put(url, data);
};

// 封装delete请求
export const del = async <T>(url: string, params?: any): Promise<T> => {
  return request.delete(url, { params });
};

// 封装文件上传请求
export const upload = async <T>(url: string, formData: FormData): Promise<T> => {
  return request.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};

export default request; 